package com.googlecode.i78ba.login;

import java.sql.Timestamp;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.googlecode.i78ba.util.StringUtil;

import com.googlecode.i78ba.util.ServiceException;

@Service
@Transactional(rollbackFor = Throwable.class, noRollbackFor = ServiceException.class)
public class LoginService {
	private static Logger log = LoggerFactory
			.getLogger(LoginService.class);

	@Autowired
	private UserMapper userMapper;

	public void register(User user){
		user.setRegister_time(new Timestamp(System.currentTimeMillis()));
		userMapper.insert(user);
	}
	
	public User login(User loginUser) throws ServiceException {
		if (StringUtil.isEmpty(loginUser.getName())) {
			throw new ServiceException("login_username_empty");
		}
		if (StringUtil.isEmpty(loginUser.getPassword())) {
			throw new ServiceException("login_password_empty");
		}
		User user = userMapper.findByName(loginUser.getName());
		log.debug("login user:" + user);
		if (user == null) {
			throw new ServiceException("login_user_not_exist");
		}
		if (!user.getPassword().equals(loginUser.getPassword())) {
			throw new ServiceException("login_password_wrong");
		}
		return user;
	}
}
